import base64
import shelve
import subprocess
from typing import List

from appium.options.android import UiAutomator2Options
from appium.webdriver import webdriver
from appium.webdriver.webdriver import WebDriver
import os

from Android.bean.ZiYuanBean import ZiYuanBean
from util import Utilkv


def getDriver():
    # def pcPushFileAndroid(driver: WebDriver):
    capabilities = dict(
        platformName='Android',  # 必填，指定平台为Android
        automationName='uiautomator2',  # 必填， 指定自动化引擎为UiAutomator2
        noReset=True,
    )

    # 定义Appium服务器URL测试地址
    appium_server_url = 'http://localhost:4723'
    # 启动测试
    driver = webdriver.Remote(appium_server_url, options=UiAutomator2Options().load_capabilities(capabilities))
    # 假设已经创建了 driver 对象和启动了应用的会话

from appium import webdriver
from appium.options.android import UiAutomator2Options

#########################################################################
#手机根目录
phone_file_root_path = '/storage/emulated/0'
'''
在手机上创建目录，
需要adb shell 命令
需要重起appium服务器，命令：npx appium --relaxed-security
'''
def create_file_on_android(driver: WebDriver):
    try:
        remote_file_path = '/storage/emulated/0/dy1/'
        #创建目录
        result = driver.execute_script('mobile: shell', {
            'command': 'mkdir',
            'args': ['-p', remote_file_path],
            'includeStderr': True,
            'timeout': 5000
        })

        # 检查结果
        if result.get('stderr'):
            print(f"创建目录时出错: {result['stderr']}")
        else:
            print(f"目录已创建，文件路径：{remote_file_path}")
            notify_media_scanner(driver, remote_file_path)

        # 目标设备上的文件路径
        # remote_file_path = '/storage/emulated/0/dy/newfile.txt'
        remote_file_path = '/storage/emulated/0/dy1/newfile.txt'
        file_content = '创建成功.'

        # 执行 ADB 命令在设备上创建文件并写入内容
        result = driver.execute_script('mobile: shell', {
            'command': 'echo',
            'args': [file_content, '>', remote_file_path],
            'includeStderr': True,
            'timeout': 5000
        })

        # 检查结果
        if result.get('stderr'):
            print(f"创建文件时出错: {result['stderr']}")
        else:
            print(f"文件已创建，文件路径：{remote_file_path}")
            notify_media_scanner(driver, remote_file_path)

    except Exception as e:
        print(f"创建文件时出错: {str(e)}")
    finally:
        # 关闭 driver 对象
        driver.quit()

'''
remote_file_path:要创建的手机目录
在手机上创建目录，
需要adb shell 命令
需要重起appium服务器，命令：npx appium --relaxed-security
'''
def create_file_on_android_mkdir(driver: WebDriver,remote_file_path):
    try:
        #手机目录
        # remote_file_path = '/storage/emulated/0/dy1/'
        #创建目录
        result = driver.execute_script('mobile: shell', {
            'command': 'mkdir',
            'args': ['-p', remote_file_path],
            'includeStderr': True,
            'timeout': 5000
        })

        # 检查结果
        if result.get('stderr'):
            print(f"创建目录时出错: {result['stderr']}")
        else:
            print(f"目录已创建，文件路径：{remote_file_path}")
            notify_media_scanner(driver, remote_file_path)


    except Exception as e:
        print(f"创建文件时出错: {str(e)}")
    # finally:
        # 关闭 driver 对象
        # driver.quit()

'''
判断手机目录是否存在
'''
def check_directory_exists(driver, directory_path):
    try:
        # 执行 ADB 命令 ls 判断目录是否存在
        result = driver.execute_script('mobile: shell', {
            'command': 'ls',
            'args': [directory_path],
            'includeStderr': True,
            'timeout': 5000
        })

        # 检查执行结果
        if result.get('stderr'):
            if 'No such file or directory' in result['stderr']:
                print(f"目录 {directory_path} 不存在")
                return False
            else:
                print(f"执行 ls 命令时出错: {result['stderr']}")
                return False
        else:
            print(f"目录 {directory_path} 已存在")
            return True

    except Exception as e:
        print(f"执行 ls 命令时出错: {str(e)}")
        return False


'''
删除和更新媒体库需要adb shell 命令
需要重起appium服务器，命令：npx appium --relaxed-security
'''
def pcPushFileAndroid(driver: WebDriver,local_file_path,remote_file_path):
    try:
        # 电脑文件路径
        # local_file_path = 'D:\\dy\\shipin\\1.mp4'

        # 手机路径
        # remote_file_path = '/storage/emulated/0/dy/1.mp4'

        # 读取本地文件的内容
        with open(local_file_path, 'rb') as file:
            file_data = base64.b64encode(file.read()).decode('utf-8')

        # 使用 push_file 方法将文件推送到设备上
        driver.push_file(remote_file_path, file_data)

        print(f"文件已传输到设备路径：{remote_file_path}")



        # 最后记得关闭 driver 对象
        # driver.quit()
    except Exception as e:
        print(f"发送文件命令时出错: local_file_path={local_file_path},remote_file_path={remote_file_path}")
        print(f"发送文件命令时出错: {str(e)}")

'''
删除手机上的文件
'''
def delete_file_from_device(driver, remote_file_path):
    try:
        # 构建 ADB 命令
        adb_command = f"adb shell rm {remote_file_path}"

        # 执行 ADB 命令
        result = driver.execute_script('mobile: shell', {
            'command': 'rm',
            'args': [remote_file_path],
            'includeStderr': True,
            'timeout': 5000
        })

        # 检查结果
        if result.get('stderr'):
            print(f"删除文件时出错: {result['stderr']}")
        else:
            print(f"文件已删除: {remote_file_path}")
    except Exception as e:
        print(f"执行删除文件命令时出错: {str(e)}")


'''
通知更新媒体库，在相册能立马看到
'''
def update_media_gallery(driver, remote_file_path):
    try:
        # 执行 ADB 命令
        result = driver.execute_script('mobile: shell', {
            'command': 'am',
            'args': ['broadcast', '-a', 'android.intent.action.MEDIA_SCANNER_SCAN_FILE', '-d', f'file://{remote_file_path}'],
            'includeStderr': True,
            'timeout': 5000
        })

        # 检查结果
        if result.get('stderr'):
            print(f"通知媒体扫描器时出错: {result['stderr']}")
        else:
            print(f"媒体库已更新，文件路径：{remote_file_path}")
    except Exception as e:
        print(f"执行通知媒体扫描器命令时出错: {str(e)}")


'''
这个代码无效
通知更文件夹，在文件夹能立马看到
'''
def notify_media_scanner(driver, directory_path):
    try:
        # 执行 ADB 广播命令通知媒体扫描器更新媒体库
        result = driver.execute_script('mobile: shell', {
            'command': 'am',
            'args': ['broadcast', '-a', 'android.intent.action.MEDIA_SCANNER_SCAN_FILE', '-d', f'file://{directory_path}'],
            'includeStderr': True,
            'timeout': 5000
        })

        # 检查执行结果
        if result.get('stderr'):
            print(f"通知媒体扫描器时出错: {result['stderr']}")
        else:
            print(f"媒体库已更新，目录路径：{directory_path}")

    except Exception as e:
        print(f"执行通知媒体扫描器命令时出错: {str(e)}")




# 定义 ZiyuanBean 类



'''
获取pc目录下的所有文件
'''
def ziyuan(directory):
    # 目标目录
    # directory = r'D:\dy\shipin'
    # 创建一个空集合来存储 ZiyuanBean 对象
    list1:list[ZiYuanBean] =[]

    # 遍历目录下的所有文件
    #  os.walk(directory)遍历目标目录及其子目录中的所有文件
    #root, dirs, files是os.walk()每次迭代返回三个值
    #分别是目录路径、当前目录下的子目录列表、以及当前目录下的文件列表
    for root, dirs, files in os.walk(directory):
        # 循环遍历每个文件。
        for file in files:
            #file='1.mp4'文件名称，
            #root='D:\\dy\\shipin'是file在root的路径下，指的是file的所在路径
            # 构造文件的完整路径'D:\\dy\\shipin\\1.mp4'
            filepath = os.path.join(root, file)
            # 创建 ZiyuanBean 对象并添加到集合中
            ziyuan_obj = ZiYuanBean(file, filepath)
            list1.append(ziyuan_obj)


    # 打印集合中的所有 ZiyuanBean 对象信息（可选）
    for ziyuan in list1:
        print(f"文件名: {ziyuan.filename}, 文件路径: {ziyuan.filepath}")
    return  list1


def ziyuan2(directory):
    # 创建一个空列表来存储 ZiyuanBean 对象
    list1: List[ZiYuanBean] = []

    # 遍历目录下的所有文件
    for root, dirs, files in os.walk(directory):
        # 循环遍历每个文件
        for file in files:
            # 构造文件的完整路径
            filepath = os.path.join(root, file)
            # 创建 ZiyuanBean 对象并添加到列表中
            ziyuan_obj = ZiYuanBean(file, filepath)
            list1.append(ziyuan_obj)

    # 根据文件的修改时间排序列表
    list1_sorted = sorted(list1, key=lambda x: os.path.getmtime(x.filepath))

    # 打印排序后的 ZiyuanBean 对象信息（可选）
    for ziyuan in list1_sorted:
        print(f"文件名: {ziyuan.filename}, 文件路径: {ziyuan.filepath}")

    return list1_sorted





# 执行 adb 命令获取指定目录及其子目录中的所有文件
def get_phone_files(directory):
    files = []
    # 使用 adb shell find 命令获取所有文件
    command = f'adb shell find {directory} -type f'
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = process.communicate()

    if process.returncode == 0:
        files = out.decode('utf-8').splitlines()
    else:
        print(f"Error occurred: {err.decode('utf-8')}")


    print(f'Files in directory ={directory}\nfiles={files}')
    return files





if __name__ == '__main__':
    print('')
    # ziyuan(r'D:\dy\shipin')
    # get_all_files(f'{phone_file_root_path}/dy')
